package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.DeleteTeachplanDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;



    /**
     * 查询课程计划树状图
     *
     * @param courseId 课程id
     * @return
     */
    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {

        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划
        if (id != null) {
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        } else {
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count + 1);
            BeanUtils.copyProperties(teachplanDto, teachplanNew);

            teachplanMapper.insert(teachplanNew);

        }

    }

    /**
     * 删除课程计划
     *
     * @param
     * @return
     */
    @Override
   // public DeleteTeachplanDto deleteTeachplan(Long courseId) {
        public void deleteTeachplan(Long courseId) {

//        //判断课程计划是否有子级
//        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Teachplan::getParentid, teachplanId);
//        int count = teachplanMapper.selectCount(queryWrapper);
//        DeleteTeachplanDto deleteTeachplanDto = new DeleteTeachplanDto();
//        if (count > 0) {
//
//            deleteTeachplanDto.setErrCode(120409);
//            deleteTeachplanDto.setErrMessage("课程计划信息还有子级信息，无法操作");
//            XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
//            //throw new XueChengPlusException("课程计划信息还有子级信息，无法操作");
//            return deleteTeachplanDto;
//        } else {
//
//            //删除课程计划
//            teachplanMapper.deleteById(teachplanId);
//            deleteTeachplanDto.setErrCode(200);
//            return deleteTeachplanDto;
//        }

        //根据courseId查询课程计划，然后通过parentId判断是小章节还是大章节
        Teachplan teachplan = teachplanMapper.selectById(courseId);
        if (teachplan.getParentid() != 0) {
            //证明是小章节
            //根据mediaType属性判断小章节是否关联视频
            String mediaType = teachplan.getMediaType();
            if (mediaType == null) {
                //证明没有关联视频或者文档
                //删除小章节
                teachplanMapper.deleteById(teachplan);
            } else {
                //证明关联了视频或者文档
                //删除视频，暂不考虑文档的情况
                teachplanMediaMapper.deleteById(courseId);
                //删除小章节
                teachplanMapper.deleteById(teachplan);
            }
            //
        } else {
            //证明是大章节
            //判断大章节下面是否有小节
            Long aLong = teachplanMapper.selectBigFest(courseId);
            if (aLong == 0) {
                //证明没有小节，可以进行删除
                teachplanMapper.deleteById(teachplan);
            } else {
                //有小节，不能删除
                XueChengPlusException.cast("课程计划信息还有子级信息，无法操作", 120409);
            }

        }

    }

    /**
     * 课程计划向下移动
     *
     * @param teachplanId
     */
    @Override
    public void moveDown(Long teachplanId) {
        //课程计划向下移动
        //根据courseId查询课程计划，然后通过parentId判断是小章节还是大章节
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan.getParentid() != 0) {
            Integer orderby = teachplan.getOrderby();
            //证明是小章节
            //根据父章节的id，找出大章节下面所有小节点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, teachplan.getParentid()).eq(Teachplan::getGrade, 2);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t :
                    teachplans) {
                //找到当前章节的排序字段加一,以此获得下一个章节
                if (t.getOrderby() == orderby + 1) {
                    i++;
                }
                if (i == 1) {
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if (i == 0) {
                XueChengPlusException.cast("当前计划已经在末尾，无法交换");
            }

        } else {
            Integer orderby = teachplan.getOrderby();
            //证明是大章节
            //根据课程的id，找到下一个大章节
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getGrade, 1);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t :
                    teachplans) {
                //找到当前章节的排序字段加一,以此获得下一个章节
                if (t.getOrderby() == orderby + 1) {
                    i++;
                }
                if (i == 1) {
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if (i == 0) {
                XueChengPlusException.cast("当前计划已经在末尾，无法交换");
            }
        }

    }

    /**
     * 课程计划向下移动
     */
    @Override
    public void moveUp(Long teachplanId) {
        //课程计划向上移动
        //根据courseId查询课程计划，然后通过parentId判断是小章节还是大章节
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan.getParentid() != 0) {
            Integer orderby = teachplan.getOrderby();
            //证明是小章节
            //根据父章节的id，找出大章节下面所有小节点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, teachplan.getParentid()).eq(Teachplan::getGrade, 2);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t :
                    teachplans) {
                //找到当前章节的排序字段减一,以此获得上一个章节
                if (t.getOrderby() == orderby - 1 && (orderby - 1) != 0) {
                    i++;
                }
                if (i == 1) {
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if (i == 0) {
                XueChengPlusException.cast("当前计划已经在顶部，无法交换");
            }

        } else {
            Integer orderby = teachplan.getOrderby();
            //证明是大章节
            //根据课程的id，找到上一个大章节
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getGrade, 1);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int i = 0;
            for (Teachplan t :
                    teachplans) {
                //找到当前章节的排序字段减一,以此获得上一个章节
                if (t.getOrderby() == orderby - 1 && (orderby - 1) != 0) {
                    i++;
                }
                if (i == 1) {
                    //进行交换
                    teachplan.setOrderby(t.getOrderby());
                    t.setOrderby(orderby);
                    teachplanMapper.updateById(t);
                    teachplanMapper.updateById(teachplan);
                    break;
                }
            }
            if (i == 0) {
                XueChengPlusException.cast("当前计划已经在顶部，无法交换");
            }
        }
    }

    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
       //先删除原有记录，根据课程计划id删除它绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,bindTeachplanMediaDto.getTeachplanId()));
       //进行新纪录验证
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }

        //再添加新记录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto,teachplanMedia);
        teachplanMedia.setCourseId(teachplan.getCourseId());//获取课程计划id
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }


    /**
     * @param courseId 课程id
     * @param parentId 父课程计划id
     * @return int 最新排序号
     * @description 获取最新的排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId, long parentId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId);
        queryWrapper.eq(Teachplan::getParentid, parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }


}
